﻿using System;
using System.Collections.Generic;
using System.Linq;
using Simple.Data;
using Model.User;

namespace Model.Communication
{
    public class Post
    {
        protected DateTime created;
        protected String content;
        protected Int32 id;
        protected Int32 topicId;
        protected Int32 authorId;

        protected Post()
        {
        }

        protected Post(int id, DateTime created, String content, int topicId, int authorId)
        {
            this.id = id;
            this.created = created;
            this.content = content;
            this.topicId = topicId;
            this.authorId = authorId;
        }

        public static Post create(String content, DateTime created, Topic topic, Person person)
        {
            var post = Database.Open().Post.Insert(content: content, Created: created, 
                                                    Topic: topic.getId(), Author: person.getId());

            return new Post(post.id, post.created, post.content, post.topic, post.author);
        }

        public static int getCount(Topic topic)
        {
            return Database.Open().Post.GetCountByTopic(topic.getId());
        }

        public static Post[] get(Topic topic, int amount, int skip)
        {
            var postsRows = Database.Open().Post.FindAllByTopic(topic.getId()).
                                                                    Skip(skip).Take(amount);

            List<Post> posts = new List<Post>();

            foreach (var p in postsRows)
            {
                posts.Add(new Post(p.id, p.created, p.content, p.topic, p.author));
            }

            return posts.ToArray();
        }

        public static Post[] getAll(Topic topic)
        {
            int count = getCount(topic);
            return get(topic, count, 0);
        }

        public int getId()
        {
            return id;
        }

        public int getAuthorId()
        {
            return authorId;
        }

        public int getTopicId()
        {
            return topicId;
        }

        public DateTime getCreated()
        {
            return created;
        }

        public String getContent()
        {
            return content;
        }

        public void setContent(String content)
        {
            this.content = content;
            Database.Open().Post.UpdateById(Id: id, Content: content);
        }

    }
}